import requests
from lxml import etree
import csv

pages = int(input('爬多少页？'))
for page in range(1, pages + 1):
    csv_headers = ['用户名', '评论', '回复数量', '喜欢数量']
    g = open('./第%s页数据.csv' % page, 'w', encoding='utf-8')
    g_csv = csv.writer(g)
    g_csv.writerow(csv_headers)
    url = 'https://www.juzikong.com/works/2cb94e93-049f-4082-85b1-c344485d6d76?page=%s' % page
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36',
        'Cookie': '__gads=ID=6a52f15f2092193c-22e9d1d1dec400aa:T=1606116819:RT=1606116819:S=ALNI_MaNdIzQFzcXCrhays08swllICB_4g; Hm_lvt_bdf284068ceac91d2241963e43550528=1606116821; _ga=GA1.2.961194859.1606116820; _gid=GA1.2.742626322.1606116822; Hm_lpvt_bdf284068ceac91d2241963e43550528=1606116868'
    }
    r = requests.get(url=url, headers=headers)
    html = etree.HTML(r.content.decode('utf-8'))
    user_name = html.xpath(
        '//*[@id="__layout"]/div/div[3]/div[1]/div[2]/div[2]/section/div[1]/a[@class="nickname_2OtJR"]/text()')
    # 列表去换行符
    user_name = [x.strip() for x in user_name]
    comment = html.xpath('//*[@id="__layout"]/div/div[3]/div[1]/div[2]/div[2]/section/div/a/span/span/span/text()')
    reply = html.xpath('//*[@id="__layout"]/div/div[3]/div[1]/div[2]/div[2]/section/div[3]/a/span/text()')
    like = html.xpath('//*[@id="__layout"]/div/div[3]/div[1]/div[2]/div[2]/section/div[3]/span[1]/span/text()')
    # print(user_name, comment, reply, like)
    # print(user_name_new)
    for i in range(0, 10):
        info = user_name[i], comment[i], reply[i], like[i]
        print('第%s页爬取完成' % i)
        g_csv.writerow(info)
